package com.atguigu.tingshu;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2024-05-09 09:36
 */
@Slf4j
public class ThreadLocalDemo {

    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    /**
     * ThreadLocal：本地线程，如果多线程下需要每个线程都有自己独立一份数据，线程间数据互相隔离。
     *
     * @param args
     */
    public static void main(String[] args) {
        //模拟线程A存入“自己”数据,在当前线程生命周期内获取“自己数据”
        for (int i = 0; i < 50; i++) {
            int finalI = i;
            new Thread(() -> {
                threadLocal.set("param"+ finalI);
                log.info("线程：{}，业务执行", Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                String param = threadLocal.get();
                log.info("线程:{}中再次获取到tl中数据:{}",Thread.currentThread().getName(), param);

            }, "thread-"+i).start();
        }
    }
}
